import { Component, OnInit } from '@angular/core';
import {Path} from "../../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../../util/page-subject";
import {ResponseUtil} from "../../../../../util/response-util";
import {OneDialogService} from "../../../../../widgets/one-dialog/one-dialog.service";
import {TraceAnalyzeService} from "../trace-analyze.service";
import {MsgResult} from "../../../../../models/msg-result";
import {MsgConstants} from "../../../../../constants/constants";
import {TraceAnalyze} from "../trace-analyze";
import {ActivatedRoute, Router} from "@angular/router";

declare var $;
declare var echarts;
declare var moment;

@Component({
  selector: 'app-trace-analyze-chart',
  templateUrl: './trace-analyze-chart.component.html',
  styleUrls: ['./trace-analyze-chart.component.css']
})
export class TraceAnalyzeChartComponent implements OnInit {

  windDirective;
  siteName: string = '';
  standData : any;
  suggest: string = '';

  traceAnalyze : TraceAnalyze;

  occurTime: string = '';
  isAlert: string;
  selectOccurTime: string = '';
  dataType: string = '';
  siteCode: string = '';
  selectDate : string = '';
  traceDateArr : Array<any> = [];
  isLoading: boolean = false;

  constructor(
    private pageSubject : PageSubject,
    private responseUtil :ResponseUtil,
    private dialogService: OneDialogService,
    private traceAnalyzeService: TraceAnalyzeService,
    private router: Router,
    private route: ActivatedRoute,
  ) {
    this.traceAnalyze = new TraceAnalyze();
  }

  ngOnInit() {
    this.pushPage();
    this.initTestData();
    this.initTime();
    this.initAddChartData();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("溯源分析", "");
    this.pageSubject.pushPage("溯源分析图表", "", path);
  }

  initTestData(){
    /**
     * http://localhost:8080/api/standardSiteData/findTraceabilityDataBySiteCodeAndTime?format=json&siteCode=410100052&occurTime=2017-09-19 10:00:00&dataType=history
     * @type {string}
     */
    this.siteCode = this.route.snapshot.params['siteCode'];
    // this.siteCode = '410100052';
    this.occurTime = moment(this.route.snapshot.params['time']).format('YYYY-MM-DD HH:mm:00');
    // this.occurTime = '2017-09-22 '
    this.isAlert = this.route.snapshot.params['alert'];
    this.dataType = 'history';
    this.windDirective = {"N":{name:"北风",direct:0},"NE":{name:"东北风",direct:45},"NW":{name:"西北风",direct:315},"E":{name:"东风",direct:90},"W":{name:"西风",direct:270},"S":{name:"南风",direct:180},"SE":{name:"东南风",direct:135},"SW":{name:"西南风",direct:225},"ESWN":{name:"旋风",direct:0}};
    // this.traceAnaChart(this.testData,'test');
    this.standData = {
      so2: '',
      aqiLevel: '',
      aqiLevelType:'',
      o3: '',
      co: '',
      no2: '',
      pm10: '',
      aqi: '',
      pm25: ''
    };
  }
  //初始化时间插件

  initAddChartData(){
    if ( this.isAlert == 'true' ) {
      this.getTraceAnalyze();
    } else {
      this.getRealTrace();
    }
  }

  initTime =() =>{
    let timeData = moment().subtract(1,"h").format("YYYY-MM-DD");
    let config = {
      singleDatePicker: true,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      maxDate:timeData,
      locale:{
        format:"YYYY-MM-DD",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate: timeData,
      endDate: timeData
    };
    $("#traceDate").daterangepicker(config).on('hide.daterangepicker', ( e ) => {
      this.selectDate = e.target.value;
      this.getTraceNum();
    })
  };
  changeDate(e){
    if(e.target.value){
      this.occurTime = this.traceDateArr[e.target.value].monitorTime;
      this.getTraceByTime();
    }
  }
  // 显示图表
  traceAnaChart = (dataList,elemId,name,type) => {
    let siteDataChart = echarts.init(document.getElementById(elemId));
    let siteDataOption = {
      tooltip: {
        trigger: 'axis'
      },
      title: {
        text: name
      },
      grid:{
        right:38,
        left:38,
        top:40,
        bottom:40
      },
      // color:["#49D3C7","#83B9D7","#81C8AC","#1A7853","#23A974","#51635C","#49D374"],
      legend:{
        data:dataList.name,
        textStyle: {
          color: "#838385"
        },
        selectedMode: "single",
        // left:"auto",
        // right:"auto",
        // itemWidth:9,
        // itemHeight:9
      },
      xAxis: {
        type: 'category',
        nameGap: "20",
        nameLocation: "start",
        splitLine: {
          show: false
        },
        data: dataList.time,
        axisLine: {
          lineStyle: {
            color: "#919191"
          }
        },
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          textStyle: {
            color: "#79797B"
          }
        },
        boundaryGap: false
      },
      yAxis: [
        {
          type: 'value',
          splitLine: {
            show: false
          },
          position:'left',
          axisLine: {
            lineStyle: {
              color: "#919191"
            }
          },
          axisLabel: {
            textStyle: {
              color: "#79797B"
            }
          }
        },
        {
          type: 'value',
          position:'right',
          splitLine: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: "#919191"
            }
          },
          axisLabel: {
            textStyle: {
              color: "#79797B"
            }
          }
        }
      ],
      series: [

      ]
    };
    let directIndex = dataList.name.indexOf('风向');
    let directArr = dataList.data[directIndex];
    if(type === 'smallSite'){
      directArr.forEach((val,i)=>{
        if(this.windDirective[val].hasOwnProperty('direct')){
          directArr[i] = this.windDirective[val].direct;
        }
      });
    }
    dataList.name.forEach((name,i) => {
      let seriesObj: any;
      if(name != '风向'){
        if(name == '风力' || name == '风速'){

        }else{
          seriesObj =  {
            name: name,
            type: 'line',
            smooth: true,
            data: dataList.data[i],
            yAxisIndex:0
            // symbolSize: 6,
            // data: this.barColor(, "aqi")
          };
        }
        siteDataOption.series.push(seriesObj)
      }

    });
    siteDataChart.setOption(siteDataOption);
  };
  getRealTrace(){
    this.isLoading = true;
    this.traceAnalyzeService.getRealTrace(this.siteCode,this.occurTime).subscribe(
      result => this.responseUtil.success(result, this.handleAnalyzeResult),
      message => this.responseUtil.error(message)
    )
  }
  getTraceAnalyze(){
    this.isLoading = true;
    this.traceAnalyzeService.getTraceAnalyze(this.siteCode,this.dataType).subscribe(
      result => this.responseUtil.success(result, this.handleAnalyzeResult),
      message => this.responseUtil.error(message)
    )
  }
  getTraceByTime(){
    this.isLoading = true;
    this.traceAnalyzeService.getTraceByTime(this.siteCode,this.occurTime,this.dataType).subscribe(
      result => this.responseUtil.success(result, this.handleAnalyzeResult),
      message => this.responseUtil.error(message)
    )
  }
  private handleAnalyzeResult = (result: MsgResult) => {
    this.isLoading = false;
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      $(".raiseDust>.box-body").html('').parent().hide();
      $(".smallSite>.box-body").html('').parent().hide();
      $(".pollution>.box-body").html('').parent().hide();
      if(result.data && result.data.hasOwnProperty('standSite')){
        if ( result.data.hasOwnProperty('suggest') ) {
          this.suggest = result.data.suggest;
        }
        let traceAnalyze = result.data;
        this.standData = traceAnalyze.standSite.monitorData;
        this.standData.aqiLevelType = this.standData.aqiLevel == '1'?'优':this.standData.aqiLevel == '2'?'良':this.standData.aqiLevel == '3'?'轻度污染':this.standData.aqiLevel == '4'?'中度污染':this.standData.aqiLevel == '5'?'严重污染':this.standData.aqiLevel == '6'?'重度污染':' ';
        this.siteName = traceAnalyze.standSite.siteName;
        traceAnalyze.raiseDust = this.dataFormatter(traceAnalyze.raiseDust,'raiseDust');
        traceAnalyze.smallSite = this.dataFormatter(traceAnalyze.smallSite,'smallSite');
        traceAnalyze.pollution = this.dataFormatter(traceAnalyze.pollution,'pollution');
        this.batchAddFormatterChart(traceAnalyze.raiseDust,'raiseDust');
        this.batchAddFormatterChart(traceAnalyze.smallSite,'smallSite');
        this.batchAddFormatterChart(traceAnalyze.pollution,'pollution');
      }else{
        this.dialogService.info('暂无数据');
      }
    } else if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 未转换
   * @param data
   * @param parentClass
   */
  batchAddChart(data,parentClass){
    if( data && data.length > 0 ){
      let raiseHtml = '';
      let raiseCodeArr: Array<any> = [];
      data.forEach((raiseData,i)=>{
        raiseCodeArr.push(raiseData.siteCode);
        raiseHtml += ' <div class="one-trace-chart">' +
          ' <div style="width: 100%;height: 100%;" id="'+raiseData.siteCode+'"></div>'+
          '</div>'
      });
      $('.'+parentClass+'>.box-body').html(raiseHtml).parent().show();
      raiseCodeArr.forEach((siteCode,i)=>{
        let raiseObj = data[i];
        this.traceAnaChart(raiseObj.historyData,siteCode,raiseObj.siteName,parentClass);
      })
    }
  }

  /**
   * 转换数据
   * @param formatterData
   * @returns {Array}
   */
  dataFormatter(formatterData,type){
    if(formatterData && formatterData.length > 0){
      let raiseFactorName = [];

      let raiseFactorData = [];

      let raiseFactorTime = [];

      formatterData.forEach((val,i)=>{
        if(i === 0){
          raiseFactorName = val.historyData.name ;
        }
        raiseFactorTime = raiseFactorTime.concat(val.historyData.time);
        raiseFactorTime.sort();
        raiseFactorData.push({
          siteName:val.siteName,
          historyData: {data:val.historyData.data,time:val.historyData.time},
          testRaiseData: []
        });
      });
      let res = [];
      let json = {};
      raiseFactorTime.forEach((item,index) => {
        if(!json[raiseFactorTime[index]]){
          res.push(raiseFactorTime[index]);
          json[raiseFactorTime[index]] = 1;
        }
      });
      raiseFactorTime = res;
      let timeData = [];
      raiseFactorTime.forEach((item) => {
        timeData.push('-');
      });

      raiseFactorData.forEach((val,i)=>{
        val.testRaiseData.forEach((factor,j)=>{
          factor = timeData;
          val.testRaiseData[j] = factor;
        });
        raiseFactorName.forEach((name,i)=>{
          val.testRaiseData.push([]);
        });
        val.historyData.time.forEach((data,c)=>{
          let index = raiseFactorTime.indexOf(data);
          val.testRaiseData.forEach((factor,j)=>{
            raiseFactorTime.forEach((item,k) => {
              factor.push('-');
            });
            factor[index]  = val.historyData.data[j][c];
            val.testRaiseData[j] = factor.splice(0,raiseFactorTime.length);
          });
        });
      });
      raiseFactorData.forEach((val,i)=>{
        val.historyData = '';
        val.factorName = raiseFactorName;
        val.time = raiseFactorTime;
      });

      return raiseFactorData;
    }else{
      $('.'+type).hide();
      return [];
    }
  }
  /**
   * 转换
   * @param data
   * @param parentClass
   */
  batchAddFormatterChart(data,parentClass){
    if( data.length > 0 ){
      let raiseHtml = '';
      let raiseNameArr = [];
      let factorName = data[0].factorName;
      data.forEach((raiseData)=>{
        raiseNameArr.push(raiseData.siteName);
      });
      factorName.forEach((factor,i)=>{
        if(factor !== '风向'){
          raiseHtml += ' <div class="one-trace-chart">' +
            ' <div style="width: 100%;height: 100%;" id="'+parentClass+i+'"></div>'+
            '</div>'
        }
      });
      $('.'+parentClass+'>.box-body').html(raiseHtml).parent().show();

      // raiseCodeArr.forEach((siteCode,i)=>{
      //   let raiseObj = data[i];
      //   this.traceAnaFormatterChart(raiseObj,parentClass+i,raiseObj.siteName,parentClass);
      // })
      factorName.forEach((factor,i)=>{
        let raiseObj = {name:[],title:'',time:[],data:[],windDire:[]};
        raiseObj.title = factor;
        raiseObj.name = raiseNameArr;
        raiseObj.time = data[0].time;
        data.forEach((dataArr,j)=>{
          if(factor == '风速' ){
            let direIndex = factorName.indexOf('风向');
            raiseObj.windDire.push(data[j].testRaiseData[direIndex]);
          }
          raiseObj.data.push(data[j].testRaiseData[i]);
        });
        if ( factor !== '风向' ){
          this.traceAnaFormatterChart(raiseObj,parentClass+i,factor,parentClass);
        }
      })
    }else{

    }
  }

  /**
   * 显示图表
   * @param dataList
   * @param elemId
   * @param factorName
   * @param type
   */
  traceAnaFormatterChart = (dataList,elemId,factorName,type) => {
    let lowerFactor = '';
    if (factorName === 'PM10') {
      lowerFactor = 'pm10'
    } else if(factorName === 'AQI'){
      lowerFactor = 'aqi'
    } else if(factorName === 'PM2.5'){
      lowerFactor = 'pm25'
    } else if(factorName === 'SO2'){
      lowerFactor = 'so2'
    } else if(factorName === 'NO2'){
      lowerFactor = 'no2'
    } else if(factorName === 'CO'){
      lowerFactor = 'co'
    } else if(factorName === 'O3'){
      lowerFactor = 'o3'
    } else if(factorName === '温度'){
      lowerFactor = 'temp'
    } else if(factorName === '湿度'){
      lowerFactor = 'hum'
    } else if(factorName === '风速'){
      lowerFactor = 'wind'
    }
    let siteDataChart = echarts.init(document.getElementById(elemId));
    let siteDataOption = {
      tooltip: {
        trigger: 'axis'
      },
      title: {
        text: factorName
      },
      grid:{
        right:38,
        left:38,
        top:40,
        bottom:40
      },
      color:["#49D3C7","#83B9D7","#81C8AC","#1A7853","#23A974","#51635C","#49D374"],
      legend:{
        type: 'scroll',
        data:dataList.name,
        textStyle: {
          color: "#838385"
        },
        // selectedMode:"single multiple",
        // left:"auto",
        // right:"auto",
        // itemWidth:9,
        // itemHeight:9
      },
      xAxis: {
        type: 'category',
        nameGap: "20",
        nameLocation: "start",
        splitLine: {
          show: false
        },
        data: dataList.time,
        axisLine: {
          lineStyle: {
            color: "#919191"
          }
        },
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          textStyle: {
            color: "#79797B"
          },
          formatter: (value, index) => {
            return value.split(' ')[1];
          }
        },
        boundaryGap: true,
      },
      yAxis:{
        type: 'value',
        splitLine: {
          show: false
        },
        position:'left',
        axisLine: {
          lineStyle: {
            color: "#919191"
          }
        },
        axisLabel: {
          textStyle: {
            color: "#79797B"
          }
        }
      },
      series: [

      ]
    };
    dataList.name.forEach((name,i) => {
      let seriesObj: any;
      let data = dataList.data[i];
      if ( lowerFactor ) {
        if ( lowerFactor == 'wind' ) {
          let windArr = [];
          let windObj = {};
          dataList.data[i].forEach((val,j)=>{
            windObj = {
              value:val,
              symbol:"emptyarrow",
              symbolRotate:-(dataList.windDire[i][j]),
              symbolSize: 10,
            };
            windArr.push(windObj);
          });
          data = windArr;
        } else {
          this.barColor(dataList.data[i], lowerFactor)
        }
      }

        seriesObj = {
        name: name,
        type: type =='raiseDust'? 'bar' : "line",
        smooth: true,
        barWidth :12,
        data: data
      };
      siteDataOption.series.push(seriesObj)
    });
    siteDataChart.setOption(siteDataOption);
  };

  /**
   * 污染等级颜色
   * @param data
   * @param type
   * @returns {string}
   */
  aqiColor = (data, type) => {
    let color = "#9B9B9B";
    let levelArr = [];
    if (type == "pm10") {
      levelArr = [50, 150, 250, 350, 500]
    } else if (type == "pm25") {
      levelArr = [35, 75, 115, 150, 250]
    } else if (type == "so2") {
      levelArr = [150, 500, 650, 800, 1600]
    } else if (type == "no2") {
      levelArr = [100, 200, 700, 1200, 2340]
    } else if (type == "co") {
      levelArr = [5, 10, 35, 60, 90]
    } else if (type == "o3") {
      levelArr = [160, 200, 300, 400, 800, 1200]
    } else if (type == "hum") {
      levelArr = [20, 40, 60, 80, 100]
    } else if (type == "temp") {
      levelArr = [0, 8, 16, 24, 32]
    } else if (type == "wind") {
      levelArr = [1, 2, 3, 4, 5, 6];
    } else if (type == "aqi") {
      levelArr = [50, 100, 150, 200, 300];
    }
    color = data <= levelArr[0] ? "#61D800"
      : data > levelArr[0] && data <= levelArr[1] ? "#CCB21A"
        : data > levelArr[1] && data <= levelArr[2] ? "#F5A623"
          : data > levelArr[2] && data <= levelArr[3] ? "#F12F1C"
            : data > levelArr[3] && data <= levelArr[4] ? "#9C0D71"
              : data > levelArr[4] ? "#630445" : "#9B9B9B";
    return color;
  };
  /**
   * 根据数据显示柱状图
   * @param datas
   * @param type
   * @returns {Array}
   */
  barColor(datas, type) {
    let barData = [];
    datas.forEach((data,i) => {
      let dataColor = this.aqiColor(data, type);
      let rankingData = {
        value: data,
        itemStyle: {
          normal: {
            color: dataColor
          }
        }
      };
      barData.push(rankingData)
    });
    return barData;
  }

  getTraceNum(){
    this.traceAnalyzeService.getTraceNum(this.siteCode,this.selectDate).subscribe(
      result => this.responseUtil.success(result, this.handleNumResult),
      message => this.responseUtil.error(message)
    )
  }
  private handleNumResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      if(result.data && result.data.length > 0){
       this.traceDateArr = result.data
      }else{
        this.traceDateArr = [];
        this.dialogService.info('暂无数据');
      }
    } else if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /*
   * pollute等级
   */
  polluteLevel = (data,type) =>{
    let levelArr = [];
    if (type == "pm10") {
      levelArr = [50, 150, 250, 350, 500]
    } else if (type == "pm25") {
      levelArr = [35, 75, 115, 150, 250]
    } else if (type == "so2") {
      levelArr = [150, 500, 650, 800, 1600]
    } else if (type == "no2") {
      levelArr = [100, 200, 700, 1200, 2340]
    } else if (type == "co") {
      levelArr = [5, 10, 35, 60, 90]
    } else if (type == "o3") {
      levelArr = [160, 200, 300, 400, 800, 1200]
    } else if (type == "hum") {
      levelArr = [20, 40, 60, 80, 100]
    } else if (type == "temp") {
      levelArr = [0, 8, 16, 24, 32]
    } else if (type == "wind") {
      levelArr = [1, 2, 3, 4, 5, 6];
    } else {
      levelArr = [50, 100, 150, 200, 300];
    }
    return data <= levelArr[0] ? 1
      : data > levelArr[0] && data <= levelArr[1] ? 2
        : data > levelArr[1] && data <= levelArr[2] ? 3
          : data > levelArr[2] && data <= levelArr[3] ? 4
            : data > levelArr[3] && data <= levelArr[4] ? 5
              : data > levelArr[4] ? 6 : 7;
  };

  search(){
    this.getTraceByTime();
  }
}
